package com.mahjong.server.component.logic.handler;

import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.mina.core.session.IoSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.mahjong.server.common.Common;
import com.mahjong.server.component.logic.main.KHMahjongAction;
import com.mahjong.server.manager.OnlineManager;
import com.mahjong.server.mina.protocol.AbsMessageProtocol;
import com.mahjong.server.mina.protocol.DataBuf;
import com.mahjong.server.mina.protocol.MessageProtocol;
import com.mahjong.server.model.Player;

/**
 * 动作处理:吃 碰 杠 胡等 客户端传递参数：1吃 2碰 3杠 4胡
 * 
 * @author yougang
 * @date 2013-3-5 上午10:59:26
 * @Description
 */
@Component
@Scope("prototype")
public class HandleReq extends MessageProtocol {

  private static final byte TAG=Common.Req;

  private static final short PROTOCOL_NUM=0x0105;

  private Logger log=Logger.getLogger(this.getClass());

  KHMahjongAction action=new KHMahjongAction();

  @Autowired
  private OnlineManager onlineManager;

  // 客户端传递3个参数
  private int playerId;

  private String pai;

  private int actionNum;

  @Override
  public short getProtocolNum() {
    return PROTOCOL_NUM;
  }

  @Override
  public byte getTag() {
    return TAG;
  }

  /**
   * 执行的客户端发来的动作： 1.吃 只有一种吃法时返回null,剩余牌同步到玩家对象中,有多种吃法时 把各种吃法组装成字符串返回格式如：["筒2_4;筒2_3","筒5_4;筒6_1"] 2.碰 返回null,剩余牌同步到玩家对象中 3.杠
   * 返回null,剩余牌同步到玩家对象中 4.胡 返回null,计算番数,统计数据,牌局结束等 当参数错误时会返回-1
   */
  @SuppressWarnings("unchecked")
  public AbsMessageProtocol execute(IoSession session, AbsMessageProtocol req) {
    log.debug(this.getClass().getSimpleName() + " execute");
    String result=null;
    try {
      if(playerId < 0 || pai == null) {
        Player player=onlineManager.getPlayerById(playerId);
        String[] pais=player.getMahjongData().getShouZhong();
        if(actionNum == 1) { // 吃
          @SuppressWarnings("unused")
          Map map=action.chi(pai, pais);
          // ...处理map
        } else if(actionNum == 2) {// 碰
          pais=action.peng(pai, pais);
          // ...
        } else if(actionNum == 3) {// 杠
          pais=action.gang(pai, pais);
          // ...
        } else if(actionNum == 4) {// 胡
          // ...
        }
        return new HandleResp(result);
      } else {
        return new HandleResp("-1");
      }
    } catch(RuntimeException e) {
      e.printStackTrace();
    }
    return null;
  }

  @Override
  public void reqDecode(DataBuf buf) {
    log.debug(this.getClass().getSimpleName() + " decode");
    playerId=buf.getInt();
    pai=buf.getString();
    actionNum=buf.getInt();
  }
}
